/**
 * @author monirul
 */

goog.require('goog.dom');
goog.require('goog.ui.Button');

var ChatWidgetView =  new Class.create({
	
	initialize: function(){
	
	},
	
	init:function(o){
		var _this = this;
		if(o['parentComponentId'] != null) this._parentComponentId = o['parentComponentId'];
		//if(o['versionNo'] != null) this._versionNo = o['versionNo'];
		this._versionNo =0;
		if(o['model'] != null) _this._model = o['model'];
		if(o['controller'] != null) _this._controller = o['controller'];
		
		

		
		if(o['elements'] != null){
			_this._elements = o['elements'];
			//_this.txtMsg = o['elements']
			var b2 = new goog.ui.Button();
			var b2Lbl ='send';
			if(o['type'] != null){
				b2Lbl = 'sendRoom';
			}
		    b2.decorate(goog.dom.$(b2Lbl));
		    
		    goog.events.listen(b2, goog.ui.Component.EventType.ACTION,
		        function(e) {
		          _this.sendMessage();
		        });

		}	

		// attach model listeners
	    this._model.chatMsgListInitialized.attach(function () {
	        _this.rebuildList();
	    });
	    
	    this._model.chatMsgListUpdated.attach(function (sender,msg) {
	        _this.displayNewMessage(msg.msg);
	    });
	   
	},
	show : function () {
        this.rebuildList();
	},
	
	sendMessage: function() {
		//ChatServiceCenter.sendMessageToGameCenter(this._elements.txtMsg.value, this._model.getComponentId());
		var msg = this._elements.txtMsg.value
		if(msg != null){
			this._controller.sendMessage(msg);
		}
		this._elements.txtMsg.value = "";
	},
	
	setVersionNo : function(versionNo){
		this._versionNo = versionNo;
	},
	
	rebuildList: function() {
		this._elements.txtMsgArea.innerHTML ="";
		var mesg = this._model.getAllMessage();
		if(mesg != null){
			for(var i=0;i<mesg.length; i++){
				this._elements.txtMsgArea.innerHTML = this._elements.txtMsgArea.innerHTML + "<br/>"+mesg[i].sender+":"+ mesg[i].msg;
			}
		}
		
		this._elements.txtMsgArea.scrollTop = this._elements.txtMsgArea.scrollHeight;
	},
	
	displayNewMessage: function(mesg) {
		this._elements.txtMsgArea.innerHTML = this._elements.txtMsgArea.innerHTML + "<br/>"+mesg.sender+":"+ mesg.msg;
		this._elements.txtMsgArea.scrollTop = this._elements.txtMsgArea.scrollHeight;
	},
	
	displayAllMessage: function(mesg) {
		this._elements.txtMsgArea.innerHTML = "";
		for ( var i = 0; i < msg.length; i++) {
			this._elements.txtMsgArea.innerHTML = this._elements.txtMsgArea.innerHTML + "<br/>"+mesg.sender+":"+ mesg.msg;
		}
		this._elements.txtMsgArea.scrollTop = this._elements.txtMsgArea.scrollHeight;
	}
	
});
